using System.Collections.Generic;
using Tools.Common.ServiceLocator;
using Tools.Domain.Specifications;
using Webshop20.Domain.Catalog.Core.Products.Filter;
using Webshop20.Domain.Catalog.Factories.Contracts;
using Tools.Domain.Specifications.Tools;

namespace Webshop20.Domain.Catalog.Factories.Implementation
{
    public class FilterSpecificationFactory<T> : IFilterSpecificationFactory<T> 
    {
        private IServiceLocator serviceLocator;

        public FilterSpecificationFactory(IServiceLocator serviceLocator)
        {
            this.serviceLocator = serviceLocator;
        }

        ISpecification<T> IFilterSpecificationFactory<T>.CreateSpecification<S>(S data)
        {
            IList<ISpecification<T>> specifications = new List<ISpecification<T>>();
            var filters = serviceLocator.ResolveAll<ISpecificationFilter<T>>();

            foreach (var filter in filters)
            {
                filter.AddSpecificationTo(ref  specifications, data);
            }

            return BuildOneSpecificationFrom(specifications);
        }

        private ISpecification<T> BuildOneSpecificationFrom(IList<ISpecification<T>> specifications)
        {
            return Merge.SpecCollectionToCompositeAndSpec(specifications);
        }
    }
}